<template>
  <el-cascader
    :value="value"
    :options="dptData"
    :props="props"
    size="mini"
    separator="-"
    @change="nodeChange"
  />
</template>

<script>
import { getDepartmentListApi } from '@/api/department'
import { transListToTreeData } from '@/utils'

export default {
  props: {
    value: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      dptData: [],
      props: {
        value: 'id',
        label: 'name'
      }
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      const res = await getDepartmentListApi()
      // 调用递归函数将响应数据转化为树形结构
      this.dptData = transListToTreeData(res, 0)
    },
    nodeChange(val) {
      if (val.length) {
        this.$emit('input', val[val.length - 1])
      } else {
        this.$emit('input', null) // 如果长度为0 说明值为空
      }
    }
  }
}
</script>

<style>

</style>
